#!/usr/bin/env python

from tweepy import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy import API
import simplejson

import thread

from sys import stderr

consumer_key = 'GnIpplNa7spzanLpFW4w'
consumer_secret = 'u54jNe9PeJyW9Ki4th4dYYHxsDnNtttgezL1FG46K4'

access_token = '370740476-nWcfsURnH3S7vaMdtPCEijK3iIm6QdCUvabLEcA4'
access_secret = 'bn2YIjXHDuTifr5XPCK8aFcTrYrCNqBUy64RskN64o'

class EmotionListener(StreamListener):
	def __init__(self, api, q):
		self.api = api
		self.queue = q
		self.me = self.api.me()

	def on_data(self, data):
		tweet = simplejson.loads(data)
		try:
			if 'friends' in tweet:
				"""Friends list notification"""
				print "Logged on"
				pass
			elif 'retweeted_status' in tweet:
				"""somebody retweeted a status"""
				pass
			elif 'delete' in tweet:
				"""somebody deleted a status"""
				pass
			elif 'event' in tweet:
				"""kind of events here"""
				if tweet['event'] == 'follow':
					"""follow event"""
					if tweet['target']['id'] == self.me.id:
						"""sombody following me"""
						print "I followed by @%s(%s)"%(
							tweet['source']['screen_name'],
							tweet['source']['name'])
						self.queue.put({
							'type': 'followed',
							'userid': tweet['source']['id'],
							})
					else:
						"""I following someone"""
						print "Following @%s(%s)"%(
							tweet['target']['screen_name'],
							tweet['target']['name'])
						self.queue.put({
							'type': 'following',
							'userid': tweet['target']['id'],
							})
			else:
				if tweet['in_reply_to_user_id'] == self.me.id:
					"""mention to me"""
					print "@%s(%s) to me\n%s\n"%(
							tweet['user']['screen_name'],
							tweet['user']['name'],
							tweet['text'],
							)
					self.queue.put({
						'type': 'mention',
						'userid': tweet['user']['id'],
						'screen_name': tweet['user']['screen_name'],
						'text': tweet['text']
						})
				else:
					"""Normal tweet"""
					print "@%s(%s)\n%s"%(
							tweet['user']['screen_name'],
							tweet['user']['name'],
							tweet['text']
							)
					self.queue.put({
						'type': 'status',
						'userid': tweet['user']['id'],
						'screen_name': tweet['user']['screen_name'],
						'text': tweet['text']
						})
		except KeyError:
			print >> stderr, "Key error occured"
			print >> stderr, data

class PublicListener(StreamListener):
	def __init__(self, queue):
		self.queue = queue
	def on_data(self, data):
		try:
			tweet = simplejson.loads(data)
			if tweet['user']['lang'] != 'ko':
				return

			if 'text' not in tweet:
				return

			self.queue.put(tweet['text'])
			return True
		except KeyError:
			pass
		except:
			pass

def userstream(queue):
	auth = OAuthHandler(consumer_key, consumer_secret)
	auth.set_access_token(access_token, access_secret)
	api = API(auth)

	l = EmotionListener(api,queue)

	stream = Stream(auth, l)
	stream.userstream(async=True)
	return stream

def publicstream(queue):
	auth = OAuthHandler(consumer_key, consumer_secret)
	auth.set_access_token(access_token, access_secret)
	api = API(auth)
	l = PublicListener(queue)

	stream = Stream(auth, l)
	stream.sample(async=True)
	return stream
